//
//  JLRoutes+BPGenerateURL.m
//  BPRoutes_Example
//
//  Created by 404 on 2020/9/4.
//  Copyright © 2020 xuhongji. All rights reserved.
//

#import "JLRoutes+BPGenerateURL.h"
#import <JLRoutes/JLRRouteRequest.h>
#import <JLRoutes/JLRRouteDefinition.h>
#import "NSDictionary+BPRoutes.h"
#import "NSString+BPRoutes.h"

@interface JLRRouteDefinition (kExtension)
- (NSString *)variableNameForValue:(NSString *)value;
- (NSString *)variableValueForValue:(NSString *)value
                  decodePlusSymbols:(BOOL)decodePlusSymbols;
@end

@implementation JLRoutes (BPGenerateURL)

+ (NSString *)BP_GenerateURLWithPattern:(NSString *)pattern
                             parameters:(NSArray *)parameters{
    return [self BP_GenerateURLWithPattern:pattern parameters:parameters extraParameters:nil];
}

+ (NSString *)BP_GenerateURLWithPattern:(NSString *)pattern
                             parameters:(NSArray *)parameters
                        extraParameters:(NSDictionary *)extraParameters{
    NSString *urlPath = nil;
    @try {
        urlPath = [NSString stringWithFormat:@"/%@%@",[parameters componentsJoinedByString:@"/"],[self BP_QueryEncryptStringWithParams:extraParameters]];

    } @catch (NSException *exception) {
        return nil;
    } @finally {
        return urlPath;
    }

    return nil;
}


+ (NSDictionary *)BP_RouteParamsWithURL:(NSURL *)URL{
    
    NSString *parameterString = URL.query;
    NSMutableDictionary *parameterDic = [NSMutableDictionary new];
    if (parameterString && parameterString.length > 0) {
        
        NSArray *kvPart = [parameterString componentsSeparatedByString:@"&"];
        for (NSString * kv in kvPart) {
            
            NSArray *kvArr = [kv componentsSeparatedByString:@"="];
            if (kvArr.count == 2) {
                [parameterDic setObject:[kvArr lastObject] forKey:[kvArr firstObject]];
            }
        }
    }
    return [NSDictionary dictionaryWithDictionary:parameterDic];
}

+ (NSString *)BP_MapDictionaryToURLQueryString:(NSDictionary *)params{
    
    if (!params) {
        return @"";
    }
    NSURLComponents *components = [[NSURLComponents alloc] init];
    NSMutableArray *queryItems = [NSMutableArray array];
    
    [params enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        
        NSString *queryKey = [NSString stringWithFormat:@"%@", key];
        NSString *queryValue = [NSString stringWithFormat:@"%@", obj];
        NSURLQueryItem *item = [NSURLQueryItem queryItemWithName:queryKey value:queryValue];
        [queryItems addObject:item];
    }];
    components.queryItems = [queryItems copy];
    
    return components.URL.absoluteString;
}

+ (NSString *)BP_QueryEncryptStringWithParams:(NSDictionary *)params{
    if (!params) {
        return @"";
    }
    NSString *jsonString = [params convert2JsonString];
    return [NSString stringWithFormat:@"?param=%@",jsonString.base64_encrypt];
}

@end
